<?php
// +--------------+-------------+------+-----+---------+----------------+
// | Field        | Type        | Null | Key | Default | Extra          |
// +--------------+-------------+------+-----+---------+----------------+
// | id           | int(11)     | NO   | PRI | NULL    | auto_increment |
// | user_id      | int(11)     | YES  |     | 0       |                |
// | related_type | varchar(50) | YES  |     |         |                |
// | related_id   | int(11)     | YES  |     | 0       |                |
// | client_ip    | bigint(20)  | NO   |     | NULL    |                |
// | create_time  | int(11)     | YES  |     | 0       |                |
// | update_time  | int(11)     | YES  |     | 0       |                |
// | star_type    | varchar(6)  | YES  |     |         |                |
// +--------------+-------------+------+-----+---------+----------------+
namespace app\common\model;
use think\Loader;
use think\Config;
use think\Request;
use think\Db;
use app\common\model\Article;
class StarLog extends Base{
  protected $auto = ['client_ip'];

  protected static function init(){
    StarLog::event('after_insert', function($data){
      $attr_name = "";
      switch ($data->star_type) {
      case 'up':
        $attr_name = "star_up";
        break;
      case 'down':
        $attr_name = "star_down";
        break;
      }

      $prefix = Config::get("database.prefix");
      if(!empty($attr_name)){
        switch ($data->related_type) {
        case 'Article':
          Db::table("{$prefix}article")->where("id", $data->related_id)->setInc($attr_name);
          break;
        }
      }
      
    });
  }
  
  public function createItem($data, $option = ["unique" => true, "login" => true]){
    $res = ["status" => false, "msg" => "点赞保存失败"];

    $data["user_id"] = $this->setUserIdAttr();
    if(isset($option["unique"]) && $option["login"] == false){
      // 未登录用户可以点赞
    }else if($data["user_id"] < 1){
      $res["msg"] = "请先登录系统才点赞";
      return $res;
    }

    $data["related_type"] = ucwords($data["related_type"]);
    if(isset($option["unique"]) && $option["unique"] == false){
      // 每个用户允许点赞多次
    }else{
      $map = [
        "user_id" => $data["user_id"],
        "related_type" => $data["related_type"],
        "related_id" => $data["related_id"],
      ];
      if($this->where($map)->count()){
        $res["msg"] = "每个用户只能点赞一次";
        return $res;
      }
    }

    $validate = Loader::validate("StarLog");
    if($validate->check($data)){
      $this->save($data);
      $res = ["status" => true, "msg" => "点赞成功"];
    }else{
      $res["msg"] = $validate->getError();
    }
    return $res;
  }

  public function relatedNewestSelect($related_type, $related_id, $user_id = NULL, $limit_count = 10){
    $prefix = Config::get("database.prefix");
    $res = ["status" => true];

    $map = [
      "{$prefix}star_log.related_type" => $related_type,
      "{$prefix}star_log.related_id" => $related_id,
    ];

    $count_fields = [
      "SUM(IF({$prefix}star_log.star_type='up', 1, 0)) AS total_up_count",
      "SUM(IF({$prefix}star_log.star_type='down', 1, 0)) AS total_down_count",
    ];
    
    if(is_null($user_id)){
      $user_id = $this->setUserIdAttr();
    }
    $user_id = intval($user_id);
    if($user_id > 0){
      array_push($count_fields, "SUM(IF({$prefix}star_log.user_id={$user_id} AND {$prefix}star_log.star_type='up', 1, 0)) AS user_up_count");
      array_push($count_fields, "SUM(IF({$prefix}star_log.user_id={$user_id} AND {$prefix}star_log.star_type='down', 1, 0)) AS user_down_count");
      $res["is_login"] = true;
    }else{
      array_push($count_fields, "0 AS user_up_count");
      array_push($count_fields, "0 AS user_down_count");
      $res["is_login"] = false;
    }
    $count_item = $this->field($count_fields)->where($map)->find();
    $res["total_up_count"] = intval($count_item["total_up_count"]);
    $res["total_down_count"] = intval($count_item["total_down_count"]);
    $res["user_up_count"] = intval($count_item["user_up_count"]);
    $res["user_down_count"] = intval($count_item["user_down_count"]);

    // 详细列表只显示类型为up的记录
    $map["{$prefix}star_log.star_type"] = "up";
    $select_fields = [
      "{$prefix}star_log.id",
      "{$prefix}star_log.create_time",
      "{$prefix}user.nickname AS user_nickname",
      "{$prefix}user.avatar AS user_avatar",
    ];
    $list = $this->field($select_fields)->where($map)
                 ->join("{$prefix}user", "{$prefix}user.id={$prefix}star_log.user_id", "LEFT")
                 ->order("{$prefix}star_log.id DESC")
                 ->limit($limit_count)
                 ->select();
    $res["list"] = $list;

    return $res;
  }

  /**
   * 给ClientIP字段自动赋值
   * @Author zhanghong
   * @Date   2017-04-18
   */
  protected function setClientIpAttr(){
    $request = Request::instance();
    $int_ip = ip2long($request->ip());
    return $int_ip;
  }
}